package com.huang.service.impl;

import com.huang.domain.LoginUser;
import com.huang.domain.ResultObject;
import com.huang.entity.User;
import com.huang.service.LoginService;
import com.huang.utils.JwtUtil;
import com.huang.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author 黄自祥
 * @date 2022/05/03 18:11
 * @Description:
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisCache redisCache;
    @Override
    public ResultObject login(User user) throws RuntimeException{
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        // 账号或密码错误在全局捕获了异常
        // authenticationManager会自动调用UserDetailService实现类
        try{
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            //使用userid生成token
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            String userId = loginUser.getUser().getId().toString();
            String jwt = JwtUtil.createJWT(userId);
            //authenticate存入redis
            redisCache.setCacheObject("login:"+userId,loginUser);
            //把token响应给前端
            HashMap<String,String> map = new HashMap<>();
            map.put("token",jwt);
            return ResultObject.success(map);
        }catch (BadCredentialsException e){
            throw new RuntimeException("登陆失败");
        }catch(UsernameNotFoundException e2){
            throw new RuntimeException("登陆失败");
        }



    }

//    退出登录
    @Override
    public void logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        redisCache.deleteObject(id.toString());
        SecurityContextHolder.clearContext();
    }
}
